﻿// =================================================================== 
// 数据访问层(GDIT.DAL)
//====================================================================
// 文件：XpoHelper.cs
// 项目名称：学院网站
// 创建时间：2012-08-08
// 负责人：ChenZhiGang
// 程序集介绍：Xpo链接库（数据操作库）
// ===================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
using System.Collections;
using DevExpress.Data.Filtering;
using System.Data;

namespace GDIT.Model
{
    public class XpoHelper
    {
        /// <summary>
        /// 指定连接Session
        /// </summary>
        private static Session _MySession = new Session (XpoDefault.DataLayer);

        /// <summary>
        /// 临时添加新纪录
        /// </summary>
        /// <param name="XPC">要添加记录的集合类</param>
        /// <param name="NewXPO">要添加的新记录</param>
        /// <param name="AddList">临时保存添加记录的列表</param>
        public static void AddRecord(ref XPCollection XPC, ref PersistentClass NewXPO, ref ArrayList AddList)
        {
            _MySession.BeginTransaction();
            try
            {
                if (AddList == null) { AddList = new ArrayList(); }
                XPC.Add(NewXPO);
                AddList.Add(NewXPO);
                _MySession.CommitTransaction();
            }
            catch (Exception ex)
            {
                _MySession.RollbackTransaction();
                throw new Exception("新增记录失败");
            }
        }

        public static IDataReader SelectID(string sql)
        {
            IDbCommand command;
            IDataReader reader;
            command = _MySession.Connection.CreateCommand();
            if (_MySession.Connection.State == ConnectionState.Closed)
            {
                _MySession.Connection.Open();
            }
            command.CommandText = sql;
            reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }

        /// <summary>
        /// 临时删除记录
        /// </summary>
        /// <param name="XPC">要删除记录的集合类</param>
        /// <param name="DeleteXPO">将要被删除的记录</param>
        /// <param name="AddList">保存添加记录的列表</param>
        /// <param name="DeleteList">保存删除记录的列表</param>
        public static void DeleteRecord(ref XPCollection XPC, ref PersistentClass DeleteXPO, ref ArrayList AddList, ref ArrayList DeleteList)
        {
            _MySession.BeginTransaction();
            try
            {
                DeleteXPO.Delete();//实体对象软删除
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("DELETE 语句与 REFERENCE 约束") > 0)
                {
                    _MySession.RollbackTransaction();
                    throw new Exception("该记录被引用，不能删除！");
                    return;
                }
            }
            _MySession.RollbackTransaction();
            try
            {
                if (DeleteList == null) { DeleteList = new ArrayList(); }
                XPC.Remove(DeleteXPO);
                Boolean isInAddList = false;//是否存在添加列表
                foreach (PersistentClass item in AddList)
                {
                    if (item == DeleteXPO)
                    {
                        AddList.Remove(DeleteXPO);
                        isInAddList = true;
                        break;
                    }
                }
                if (isInAddList == false)
                {
                    DeleteList.Add(DeleteXPO);
                }
                _MySession.CommitTransaction();
            }
            catch (Exception)
            {
                _MySession.RollbackTransaction();
                throw new Exception("删除记录失败！");
            }
        }

        /// <summary>
        /// 保存添加操作，正式把记录添加到数据库中
        /// </summary>
        /// <param name="AddList">保存添加记录的临时列表</param>
        /// <returns>1:保存成功   0:保存失败</returns>
        public static int SaveAdded(PersistentClass per)
        {
            if (per == null) { return 0; }
            _MySession.BeginTransaction();
            try
            {
                string errorString = per.GetDataError();
                if (errorString != null && errorString.Trim().Length > 0)
                {
                    throw new Exception(errorString);
                    _MySession.RollbackTransaction();
                    return 0;
                }
                else
                {
                    per.Save();
                }
                _MySession.CommitTransaction();
                return 1;
            }
            catch (Exception)
            {
                _MySession.RollbackTransaction();
                throw new Exception("保存添加操作失败,请刷新后重新执行添加操作!");
                return 0;
            }
        }

        /// <summary>
        /// 保存修改集合操作
        /// </summary>
        /// <param name="XPC">要保存的数据集合类</param>
        /// <returns>True:保存成功   Fals:保存失败</returns>
        public static Boolean SaveModified(ref XPCollection XPC)
        {
            if (XPC == null) { return false; }
            _MySession.LockingOption = LockingOption.Optimistic;
            _MySession.BeginTransaction();
            try
            {
                int xpcCount = XPC.Count;
                if (xpcCount > 0)
                {
                    for (int i = xpcCount - 1; i >= 0; i--)
                    {
                        PersistentClass xpo = (PersistentClass)XPC[i];
                        if (xpo.Modified == true)
                        {
                            string errorString = xpo.GetDataError();
                            if (errorString != null && errorString.Trim().Length > 0)
                            {
                                throw new Exception(errorString);
                                _MySession.RollbackTransaction();
                                return false;
                            }
                            else
                            {
                                xpo.Save();
                            }
                        }

                    }
                }
                _MySession.CommitTransaction();
                _MySession.LockingOption = LockingOption.None;
                return true;
            }
            catch
            {
                _MySession.RollbackTransaction();
                _MySession.LockingOption = LockingOption.None;
                throw new Exception("保存修改操作失败,请刷新后重新执行修改操作!");
                return false;
            }
        }

        /// <summary>
        /// 保存对象修改操作
        /// </summary>
        /// <param name="XPC">要保存的数据对象</param>
        /// <returns>1:保存成功   0:保存失败</returns>
        public static int SaveModified(PersistentClass per)
        {
            if (per == null) { return 0; }
            _MySession.LockingOption = LockingOption.Optimistic;//处理并发开始
            _MySession.BeginTransaction();
            try
            {
                if (per.Modified == true)
                {
                    string errorString = per.GetDataError();
                    if (errorString != null && errorString.Trim().Length > 0)
                    {
                        throw new Exception(errorString);
                        _MySession.RollbackTransaction();
                        return 0;
                    }
                    else
                    {
                        per.Save();
                    }
                }
                _MySession.CommitTransaction();
                _MySession.LockingOption = LockingOption.None;//处理并发结束
                return 1;
            }
            catch
            {
                _MySession.RollbackTransaction();
                _MySession.LockingOption = LockingOption.None;//处理并发结束
                throw new Exception("保存修改操作失败,请刷新后重新执行修改操作!");
                return 0;
            }
        }

        /// <summary>
        /// 保存对象修改操作
        /// </summary>
        /// <param name="XPC">要保存的数据对象</param>
        /// <returns>1:保存成功   0:保存失败</returns>
        public static int SaveModifiedByZi(PersistentClass per)
        {
            if (per == null) { return 0; }
            _MySession.LockingOption = LockingOption.Optimistic;//处理并发开始
            _MySession.BeginTransaction();
            try
            {
                per.Save();
                _MySession.CommitTransaction();
                _MySession.LockingOption = LockingOption.None;//处理并发结束
                return 1;
            }
            catch
            {
                _MySession.RollbackTransaction();
                _MySession.LockingOption = LockingOption.None;//处理并发结束
                throw new Exception("保存修改操作失败,请刷新后重新执行修改操作!");
                return 0;
            }
        }

        /// <summary>
        /// 刷新数据集合
        /// </summary>
        /// <param name="XPC">要刷新的集合</param>
        public static void RefreshXPC(ref XPCollection XPC)
        {
            if (XPC == null) { return; }
            XPC.Reload();
            for (int i = XPC.Count - 1; i >= 0; i--)
            {
                PersistentClass xpo = (PersistentClass)XPC[i];
                xpo.Reload();
            }
        }

        public class Test<T>
        {
            public T obj;

            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="obj"></param>
            public Test(T obj)
            {

                this.obj = obj;
            }

            public Test() { }

            public int Delete(int id)
            {
                _MySession.BeginTransaction();
                try
                {
                    IDbCommand command;
                    _MySession.Connection.Open();
                    command = _MySession.Connection.CreateCommand();
                    command.CommandText = "delete from dbo."+typeof(T).Name+" where OID = "+id+"";
                    int result = (int)command.ExecuteNonQuery();
                    _MySession.Connection.Close();
                    if (result > 0)
                    {
                        _MySession.CommitTransaction();
                        return 1;
                    }
                    return 0;
                }
                catch (Exception ex)
                {
                    if (ex.Message.IndexOf("DELETE 语句与 REFERENCE 约束") > 0)
                    {
                        _MySession.RollbackTransaction();
                        throw new Exception("该记录被引用，不能删除！");
                        return 0;
                    }
                    _MySession.RollbackTransaction();
                    throw new Exception("保存删除操作失败,请刷新后重新执行删除操作!");
                    return 0;
                }
            }

            /// <summary>
            /// 对于多条件的查询的操作的方法
            /// </summary>
            /// <param name="group">组操作属性</param>
            /// <returns></returns>
            public XPCollection Operation(GroupOperator group)
            {
                return new XPCollection(typeof(T), group);
            }

            /// <summary>
            /// 对于单条件的查询的操作的方法
            /// </summary>
            /// <param name="binary">单操作属性</param>
            /// <returns></returns>
            public XPCollection Operation(BinaryOperator binary)
            {
                return new XPCollection(typeof(T), binary);
            }

            /// <summary>
            /// 对于查询相等操作操作的方法
            /// </summary>
            /// <param name="field">字段名</param>
            /// <param name="value">条件值</param>
            /// <returns></returns>
            public XPCollection Operation(string field, string value)
            {
                return new XPCollection(typeof(T), new BinaryOperator(field, value, BinaryOperatorType.Equal));
            }

            /// <summary>
            /// 对于查询相等操作操作的方法
            /// </summary>
            /// <param name="field">字段名</param>
            /// <param name="value">条件值</param>
            /// <returns></returns>
            public XPCollection Operation(string field, int value)
            {
                return new XPCollection(typeof(T), new BinaryOperator(field, value, BinaryOperatorType.Equal));
            }

            /// <summary>
            /// 对于没有条件的查询的操作方法
            /// </summary>
            /// <returns></returns>
            public XPCollection Operation()
            {
                return new XPCollection(typeof(T));
            }
        }
    }
}
